<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    /**
     * 创建圆角矩形的贝塞尔曲线路径
     * @param {number} radius - 圆角半径 (0-1 之间)
     * @returns {Array} 包含完整路径的数组
     */
    function createRoundedRectanglePath(radius, width = 1, height = 1) {
      radius = Math.min(Math.max(radius, 0), 1);
      width = Math.min(Math.max(width, 0), 1);
      height = Math.min(Math.max(height, 0), 1);

      const path = [
        // 左上角
        { type: 'start', point: [0, height - radius] },
        { type: 'control1', point: [0, height] },
        { type: 'control2', point: [radius, height] },
        { type: 'end', point: [width, height - radius] },

        // 右上角
        { type: 'start', point: [width, height - radius] },
        { type: 'control1', point: [width, height] },
        { type: 'control2', point: [width - radius, height] },
        { type: 'end', point: [width - radius, 0] },

        // 右下角
        { type: 'start', point: [width - radius, 0] },
        { type: 'control1', point: [width, 0] },
        { type: 'control2', point: [width, radius] },
        { type: 'end', point: [0, height - radius] },

        // 左下角
        { type: 'start', point: [0, height - radius] },
        { type: 'control1', point: [0, height] },
        { type: 'control2', point: [radius, height] },
        { type: 'end', point: [radius, 0] }
      ];

      return path;
    }


    // 绘制路径的函数
    function drawRoundedRectangle(ctx, path) {
      console.log(path)
      ctx.beginPath();
      ctx.moveTo(path[0].point[0], path[0].point[1]);

      for (let i = 1; i < path.length; i += 4) {
        ctx.bezierCurveTo(
          path[i].point[0], path[i].point[1],
          path[i + 1].point[0], path[i + 1].point[1],
          path[i + 2].point[0], path[i + 2].point[1]
        );
      }

      ctx.strokeStyle = 'red'
      ctx.closePath();
    }

    // 使用示例
    const canvas = document.createElement('canvas');
    canvas.width = 500;
    canvas.height = 500;
    canvas.style = 'border: 1px solid red'
    document.body.appendChild(canvas);
    const ctx = canvas.getContext('2d');

    const path = createRoundedRectanglePath(0.3); // 0.3 的圆角半径
    ctx.fillStyle = '#8cead6';

    drawRoundedRectangle(ctx, path);
    ctx.fill();

  </script>
</body>

</html>